package cool.taomu.toolkit.service.kademlia.utils

import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import org.slf4j.LoggerFactory

/**
@startuml
nwdiag {
  network 外网 {
   width = full
   client [address = "client" ]
   server [address = "client 18080" ]
   server2 [address = "client 18080" ]
 }
 network R允许从远程服务器访问本地资源{
   width = full
   client [address = "R" ]
   server [address = "R 18081,18082" ]
   server2 [address = "R 18081,18082" ]
   peer_A1 [address = "R 18080 <- 18081" ]
   peer_B2 [address = "R 18080 <- 18082" ]
  }
  network L允许从本地服务器访问远程资源 {
   server [address = "L 18080 " ]
   server2 [address = "L 18080" ]
   peer_A1 [address = "L 18082 -> 18080" ]
   peer_B2 [address = "L 18082 -> 18080" ]
 }
}
@enduml

 */
class NetwrokUtils {

	val static LOG = LoggerFactory.getLogger(NetwrokUtils);

	/**
	 * 检测主机和端口是否可连接（尝试建立 Socket 连接）
	 */
	def static boolean isAvailable(String host, int port) {
		try (var Socket socket = new Socket()) {
			socket.connect(new InetSocketAddress(host, port), 2000); // 设置超时时间
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	def static void setProxyPeer(KPeerNode peer) {
	/* 	if (peer.proxy !== null && peer.proxy.size > 0 && peer.isProxyAvailable) {
			LOG.info("通过R代理连接服务器：{}", peer)
			var rnode = peer.proxy.findFirst[it.type.equalsIgnoreCase("R")]
			if (rnode !== null && NetwrokUtils.isAvailable(rnode.host, rnode.port)) {
				LOG.info("R代理连接服务器可以用")
				peer.host = rnode.host
				peer.port = rnode.port
			} else {
				var lnode = peer.proxy.findFirst[it.type.equalsIgnoreCase("L")]
				if (lnode !== null && NetwrokUtils.isAvailable(lnode.host, lnode.port)) {
					LOG.info("L代理连接服务器可以用")
					peer.host = lnode.host
					peer.port = lnode.port
				} else {
					peer.isProxyAvailable = false;
					LOG.info("代理连接服务器不可用")
				}
			}
		}*/
	}
}
